<template>
  <div>
    <a-card :bordered="false" :bodyStyle="{ padding: '12px 0 0 12px' }">
      <a-spin :spinning="loading">
        <div style="display: flex">
          <div style="border-right: 1px solid #e8e8e8">
            <a-button type="primary" style="width: 190px" @click="add()">新建角色</a-button>
            <a-menu
              style="width: 200px; border-right: none"
              v-model="nowChoiceKey"
              mode="inline"
              :default-open-keys="['1', '2']"
            >
              <a-sub-menu key="1">
                <span slot="title">
                  <span>自定义角色</span>
                </span>
                <a-menu-item
                  v-for="(item, index) in list"
                  :key="index"
                  v-if="list.length > 0 && item.type == 1"
                  style="position: relative"
                >
                  {{ item.name }}
                  <span style="position: absolute; right: 0; top: 0; z-index: 1" v-if="item.can_delete == 1">
                    <a-icon type="delete" @click.stop="del(item.id)"></a-icon>
                  </span>
                </a-menu-item>
              </a-sub-menu>
              <a-sub-menu key="2">
                <span slot="title">
                  <span>系统角色</span>
                </span>
                <a-menu-item
                  v-for="(item, index) in list"
                  :key="index"
                  v-if="list.length > 0 && item.type == 0"
                  style="position: relative"
                  >{{ item.name }}</a-menu-item
                >
              </a-sub-menu>
            </a-menu>
          </div>
          <div class="rightContent">
            <div class="roleName">
              <span> <span style="color: red">*</span> 角色名称： </span>
              <span class="input">
                <a-input v-model="info.name" allowClear></a-input>
              </span>
            </div>
            <a-alert
              style="border-radius: 4px; background: rgb(255, 240, 231); margin-bottom: 16px"
              message="编辑角色，拥有该角色的员工的权限也将被更改，请谨慎操作"
              banner
            />
            <div class="roleContent">
              <div class="roleList">
                <h4 class="title">功能权限</h4>
                <div class="desc">决定角色可以看到哪些页面或使用哪些操作</div>
                <div class="dataList">
                  <div v-for="(item, index) in showArr" :key="index" class="treeList">
                    <a-tree
                      checkable
                      :defaultExpandParent="true"
                      :autoExpandParent="true"
                      :defaultExpandAll="true"
                      :tree-data="[item]"
                      @check="onCheck"
                      :replace-fields="replaceFields"
                      class="dataTree"
                      v-model="data[index + 1].children"
                    ></a-tree>
                  </div>
                </div>
              </div>
              <div class="roleList dataRole">
                <h4 class="title">数据权限</h4>
                <div class="desc">决定员工可查看到多少数据或内容</div>
                <div class="list">
                  <div class="content" v-if="data_permission">
                    <div class="left">
                      <h4 class="title">学员</h4>
                      <a-radio-group v-model="data_permission.student">
                        <a-radio :style="radioStyle" :value="1"
                          >全部学员<span style="color: #999">(可查看并处理机构内所有的学员)</span></a-radio
                        >
                        <a-radio :style="radioStyle" :value="2"
                          >部分学员<span style="color: #999"
                            >(仅可查看并处理分配给自己的学员、仅可查看并管理自己授课班级的在读学员)</span
                          ></a-radio
                        >
                      </a-radio-group>
                    </div>
                    <div class="right">
                      <h4 class="title">班级</h4>
                      <a-radio-group v-model="data_permission.school_class">
                        <a-radio :style="radioStyle" :value="1"
                          >全部班级<span style="color: #999">(可查看并处理机构内所有的班级)</span></a-radio
                        >
                        <a-radio :style="radioStyle" :value="2"
                          >部分班级<span style="color: #999">(仅查看并处理分配给自己的班级)</span></a-radio
                        >
                      </a-radio-group>
                    </div>
                  </div>
                  <div class="content" v-if="data_permission">
                    <div class="left">
                      <h4 class="title">课表</h4>
                      <a-radio-group v-model="data_permission.class_schedule">
                        <a-radio :style="radioStyle" :value="1"
                          >全部课表<span style="color: #999">(可查看并处理机构内所有的课表)</span></a-radio
                        >
                        <a-radio :style="radioStyle" :value="2"
                          >部分课表<span style="color: #999">(仅查看上课老师是自己的课表)</span></a-radio
                        >
                      </a-radio-group>
                    </div>
                    <div class="right">
                      <h4 class="title">上课记录</h4>
                      <a-radio-group v-model="data_permission.call_record">
                        <a-radio :style="radioStyle" :value="1"
                          >全部记录<span style="color: #999">全部记录(可查看并处理机构内所有的上课记录)</span></a-radio
                        >
                        <a-radio :style="radioStyle" :value="2"
                          >部分记录<span style="color: #999">(仅查看上课老师是自己的上课记录)</span></a-radio
                        >
                      </a-radio-group>
                    </div>
                  </div>
                  <div class="content" v-if="data_permission">
                    <div class="left">
                      <h4 class="title">缺课补课</h4>
                      <a-radio-group v-model="data_permission.missed_class">
                        <a-radio :style="radioStyle" :value="1"
                          >全部记录<span style="color: #999">(可查看并处理机构内所有的缺课补课记录)</span></a-radio
                        >
                        <a-radio :style="radioStyle" :value="2"
                          >部分记录<span style="color: #999">(可查看上课老师是自己的缺课补课记录)</span></a-radio
                        >
                      </a-radio-group>
                    </div>
                    <div class="right">
                      <h4 class="title">导入记录</h4>
                      <a-radio-group v-model="data_permission.import_histories">
                        <a-radio :style="radioStyle" :value="1"
                          >全部数据<span style="color: #999">(可查看所有导入记录)</span></a-radio
                        >
                        <a-radio :style="radioStyle" :value="2"
                          >部分数据<span style="color: #999">(仅查看自己导入的记录)</span></a-radio
                        >
                      </a-radio-group>
                    </div>
                  </div>
                  <div class="content" v-if="data_permission">
                    <div class="left">
                      <h4 class="title">导出记录</h4>
                      <a-radio-group v-model="data_permission.export_histories">
                        <a-radio :style="radioStyle" :value="1"
                          >全部数据<span style="color: #999">(可查看所有导出记录)</span></a-radio
                        >
                        <a-radio :style="radioStyle" :value="2"
                          >部分数据<span style="color: #999">(仅查看自己导出的记录)</span></a-radio
                        >
                      </a-radio-group>
                    </div>
                    <div class="right"></div>
                  </div>
                  <div class="content" v-if="data_permission">
                    <div class="left">
                      <h4 class="title">财务记录</h4>
                      <a-radio-group v-model="data_permission.order">
                        <a-radio :style="radioStyle" :value="1"
                          >全部数据<span style="color: #999">(可查看所有订单记录和收支明细记录)</span></a-radio
                        >
                        <a-radio :style="radioStyle" :value="2"
                          >部分数据<span style="color: #999"
                            >(仅查看经办人或者业绩归属人是自己的订单记录和收支明细记录)</span
                          ></a-radio
                        >
                      </a-radio-group>
                    </div>
                    <div class="right"></div>
                  </div>
                </div>
              </div>
            </div>
          <!--  <div class="config">
              <div class="title">配置</div>
              <div class="content">
                <div class="sort">
                  <div class="sortTitle">收款配置</div>
                  <a-radio-group v-model="collection_config">
                    <a-radio :style="radioStyle" :value="1">仅能用小麦收银收款</a-radio>
                    <a-radio :style="radioStyle" :value="2">可以使用所有收款方式</a-radio>
                  </a-radio-group>
                </div>
                <div class="sort">
                  <div class="sortTitle">请假审批配置</div>
                  <a-radio-group v-model="leave_config">
                    <a-radio :style="radioStyle" :value="1">接收学员请假审批结果通知</a-radio>
                    <a-radio :style="radioStyle" :value="2">不接收学员请假审批结果通知</a-radio>
                  </a-radio-group>
                </div>
              </div>
            </div> -->
            <div class="bottomBtn">
              <a-button style="margin-right: 10px" @click="getList()">取消</a-button>
              <a-button type="primary" @click="submit()" v-if="!showSubmit">保存</a-button>
              <a-button type="primary" v-if="showSubmit" @click="saveAs(info.name)">另存为</a-button>
            </div>
          </div>
        </div>
      </a-spin>
      <a-modal title="新建角色" @cancel="saveModel = false" :visible="saveModel" @ok="save">
        系统提供的角色暂时不允许修改，需要你新建一个角色进行维护.
        <a-input style="margin-top: 8px; width: 400px" v-model="saveName" placeholder="请输入新的角色名称"></a-input>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
const roleListArr = [
  { permissionId: 'Analysis', permissionIdName: '中心首页', children: [] },
  { permissionId: 'centerDashBoard', permissionIdName: '中心首页', children: [] },
  { permissionId: 'sales_indx', permissionIdName: '销售中心', children: [] },
  {
    permissionId: 'educationalCenterGroup',
    permissionIdName: '教务中心',
    children: [],
  },
  { permissionId: 'homeSchool', permissionIdName: '家校互动', children: [] },
  { permissionId: 'marketing', permissionIdName: '营销中心', children: [] },
  
  { permissionId: 'finance', permissionIdName: '财务中心', children: [] },
  { permissionId: 'settingGroup', permissionIdName: '机构设置', children: [] },
  { permissionId: 'appCenter', permissionIdName: '应用中心', children: [] },
]
import { roleList, roleInfo, dataList, addRole, editRole, roleDel } from '@/api/account'
export default {
  data() {
    return {
      loading: false,
      list: [],
      showArr: [],
      defaultArr: [],
      appCenterChildren: [],
      collection_config: 2,
      leave_config: 2,
      nowChoiceKey: null,
      info: {
        name: null,
      },
      replaceFields: {
        children: 'children',
        title: 'permissionIdName',
        key: 'permissionId',
      },
      radioStyle: {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
      },
      data: roleListArr,
      referenceArr: [],
      saveModel: false,
      saveName: undefined,
      showSubmit: false, //控制显示另存为还是保存
      radioStyle: {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
      },
      data_permission: {
        student: 1,
        class_schedule: 1,
        missed_class: 1,
        export_histories: 1,
        order: 1,
        school_class: 1,
        call_record: 1,
        import_histories: 1,
      },
      selted: false,
    }
  },

  created() {
    dataList({ school_id: this.$store.state.user.school }).then((res) => {
      let result = JSON.parse(JSON.stringify(res))
      let parmas = JSON.parse(JSON.stringify(res))
      let defaultArr = []
      let showArr = [{ children: [], permissionId: 'centerDashBoard', permissionIdName: '中心首页' }]
      this.referenceArr = []
      parmas.forEach((val) => {
        if (val.children) {
          val.children.forEach((item) => {
            this.referenceArr.push(item)
          })
        }
      })
      result.forEach((val) => {
        if (val.permissionId == 'Analysis') {
          defaultArr.push(val)
        } else {
          if (val.children) {
            if (val.permissionId == 'appCenter') {
              this.appCenterChildren = val.children
              let customChildren = val.children
              for (let i = customChildren.length - 1; i >= 0; i--) {
                if (customChildren[i].children) {
                  delete customChildren[i].children
                }
                if (customChildren[i].permissionId == 'appCenterIndex') {
                  customChildren.splice(i, 1)
                }
              }
            } else {
              val.children.forEach((item) => {
                if (item.children) {
                  delete item.children
                }
              })
            }

            showArr.push(val)
          }
        }
      })
      this.defaultArr = defaultArr
      this.showArr = showArr
      console.log(this.showArr, 333)
    })
    this.getList()

    setTimeout(() => {}, 2000)
  },
  watch: {
    nowChoiceKey(val) {
      if (val) {
        if (this.list[val[0]].type == 0) {
          this.showSubmit = true
        } else {
          this.showSubmit = false
        }
        this.getInfo(this.list[val[0]].id)
      }
    },
    saveModel(val) {
      if (!val) {
        this.saveName = undefined
      }
    },
  },
  methods: {
    saveAs(name) {
      let data = JSON.parse(JSON.stringify(name))
      this.saveName = name
      this.saveModel = true
    },
    add() {
      this.loading = true
      let that = this
      this.showSubmit = false
      setTimeout(function () {
        that.loading = false
      }, 500)
      this.nowChoiceKey = null
      this.info = {
        name: null,
      }
      this.leave_config = 2
      this.collection_config = 2
      this.data = roleListArr
      this.data_permission = {
        student: 1,
        class_schedule: 1,
        missed_class: 1,
        export_histories: 1,
        order: 1,
        school_class: 1,
        call_record: 1,
        import_histories: 1,
      }
      this.$forceUpdate()
    },
    getList(e = 0) {
      this.loading = true
      roleList({
        school_id: this.$store.state.user.school,
        pageSize: 9999999999,
      })
        .then((res) => {
          this.list = JSON.parse(JSON.stringify(res.data))
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取角色列表失败')
        })
        .finally(() => {
          this.loading = false
          if (this.list.length > 0) {
            if (e == 0) {
              this.nowChoiceKey = [0]
            } else {
              this.list.forEach((val, index) => {
                if (val.id == e) {
                  this.nowChoiceKey = [index]
                }
              })
            }
          }
        })
    },
    getInfo(e) {
      this.loading = true
      roleInfo(e, { school_id: this.$store.state.user.school })
        .then((res) => {
          this.info = JSON.parse(JSON.stringify(res))
          this.collection_config = res.collection_config
          this.leave_config = res.leave_config
          this.data_permission = res.data_permission
          let parmas = JSON.parse(JSON.stringify(res.permission))
          parmas.forEach((val) => {
            let arr = []
            if (val.permissionId == 'centerDashBoard') {
              val.children = ['centerDashBoard']
            } else if (val.permissionId == 'appCenter') {
              let customChildren = val.children
              for (let i = customChildren.length - 1; i >= 0; i--) {
                if (customChildren[i].children) {
                  delete customChildren[i].children
                }
                if (customChildren[i].permissionId == 'appCenterIndex') {
                  customChildren.splice(i, 1)
                }
              }
              let data = JSON.parse(JSON.stringify(val.children))
              let appCenterArr = []
              data.forEach((item) => {
                appCenterArr.push(item.permissionId)
              })
              val.children = appCenterArr
            } else {
              if (val.children && val.children.length > 0) {
                let data = JSON.parse(JSON.stringify(val.children))
                data.forEach((item) => {
                  arr.push(item.permissionId)
                })
              }
              val.children = arr
            }
          })
          let signArr = JSON.parse(JSON.stringify(roleListArr))
          signArr.forEach((val) => {
            parmas.forEach((item) => {
              if (val.permissionId == item.permissionId) {
                val.children = item.children
              }
            })
          })
          this.data = signArr
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取角色详情失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    submit() {
      if (!this.info.name) {
        this.$message.error('请输入角色名称~')
        return
      }
      let parmas = JSON.parse(JSON.stringify(this.data))
      let num = 0
      parmas.forEach((val) => {
        if (val.permissionId !== 'Analysis') {
          if (val.children.length == 0) {
            num++
          }
        }
      })
      if (num == roleListArr.length - 1) {
        this.$message.error('请至少选择一个权限~')
        return
      }

      this.loading = true
      console.log(this.defaultArr[0].children, 66)

      parmas.forEach((val) => {
        if (val.permissionId == 'Analysis') {
          val.children = this.defaultArr[0].children
        } else if (val.permissionId == 'appCenter' && val.children.length > 0) {
          val.children.unshift({ permissionId: 'appCenterIndex', permissionIdName: '应用中心' })
          for (let i = val.children.length - 1; i >= 0; i--) {
            if (val.children[i] == val.permissionId) {
              val.children.splice(i, 1)
            } else {
              this.referenceArr.forEach((key) => {
                if (val.children[i] == key.permissionId) {
                  val.children.splice(i, 1, key)
                }
              })
            }
          }
        } else {
          for (let i = val.children.length - 1; i >= 0; i--) {
            if (val.children[i] == val.permissionId) {
              val.children.splice(i, 1)
            } else {
              this.referenceArr.forEach((key) => {
                if (val.children[i] == key.permissionId) {
                  val.children.splice(i, 1, key)
                }
              })
            }
          }
        }
      })

      console.log(parmas, '改变前')
      for (let j = parmas.length - 1; j >= 0; j--) {
        if (parmas[j].children.length == 0 && parmas[j].permissionId !== 'centerDashBoard') {
          parmas.splice(j, 1)
        } else if (parmas[j].permissionId == 'appCenter' && parmas[j].children.length == 0) {
          parmas.splice(j, 1)
        } else if (parmas[j].permissionId == 'centerDashBoard' && parmas[j].children.length == 0) {
          parmas.splice(j, 1)
        }
      }

      if (this.selted) {
        parmas.push({
          permissionId: 'centerDashBoard',
          permissionIdName: '中心首页',
          children: [],
        })
      }
      console.log(parmas, '改变后')
      // return
      if (this.info.id) {
        editRole(
          {
            name: this.info.name,
            school_id: this.$store.state.user.school,
            permission: parmas,
            leave_config: this.leave_config,
            collection_config: this.collection_config,
            data_permission: this.data_permission,
          },
          this.info.id
        )
          .then((res) => {
            this.$message.success('保存成功')
            this.getList(this.info.id)
          })
          .catch((err) => {
            this.$message.error(err.data.message || '保存失败')
            this.loading = false
          })
      } else {
        addRole({
          name: this.info.name,
          school_id: this.$store.state.user.school,
          permission: parmas,
          leave_config: this.leave_config,
          collection_config: this.collection_config,
          data_permission: this.data_permission,
        })
          .then((res) => {
            this.$message.success('添加成功')
            this.getList(res.id)
          })
          .catch((err) => {
            this.$message.error(err.data.message || '添加失败')
            this.loading = false
          })
      }
    },
    //另存为
    save() {
      this.loading = true
      let parmas = JSON.parse(JSON.stringify(this.data))
      parmas.forEach((val) => {
        if (val.permissionId == 'Analysis') {
          //首页
          val.children = this.defaultArr[0].children
        } else if (val.permissionId == 'appCenter' && val.children.length > 0) {
          val.children.unshift({ permissionId: 'appCenterIndex', permissionIdName: '应用中心' })
          for (let i = val.children.length - 1; i >= 0; i--) {
            if (val.children[i] == val.permissionId) {
              val.children.splice(i, 1)
            } else {
              this.referenceArr.forEach((key) => {
                if (val.children[i] == key.permissionId) {
                  val.children.splice(i, 1, key)
                }
              })
            }
          }
        } else {
          for (let i = val.children.length - 1; i >= 0; i--) {
            if (val.children[i] == val.permissionId) {
              val.children.splice(i, 1)
            } else {
              this.referenceArr.forEach((key) => {
                if (val.children[i] == key.permissionId) {
                  val.children.splice(i, 1, key)
                }
              })
            }
          }
        }
      })
      for (let j = parmas.length - 1; j >= 0; j--) {
        if (parmas[j].children.length == 0) {
          parmas.splice(j, 1)
        }
      }
      addRole({
        name: this.saveName,
        school_id: this.$store.state.user.school,
        permission: parmas,
        leave_config: this.leave_config,
        collection_config: this.collection_config,
        data_permission: this.data_permission,
      })
        .then((res) => {
          this.$message.success('添加成功')
          this.saveModel = false
          this.getList(res.id)
        })
        .catch((err) => {
          this.$message.error(err.data.message || '添加失败')
          this.loading = false
        })
    },
    onCheck(checkedKeys, e) {
      // console.log(checkedKeys,e)
      // console.log(this.data)
      if (e.checked == true&&checkedKeys[0]=='centerDashBoard') {
       
        this.selted = true
      } else {
        this.selted = false
      }
    },
    del(e) {
      let that = this
      this.$confirm({
        title: '确认删除？',
        content: '删除此角色后，数据将不能恢复，确定删除？',
        onOk() {
          that.loading = true
          roleDel(e)
            .then((res) => {
              that.$message.success('删除成功')
              that.getList()
            })
            .catch((err) => {
              that.$message.error('删除失败')
              that.loading = false
            })
        },
        onCancel() {},
      })
    },
  },
}
</script>
<style lang="less" scoped>
.rightContent {
  padding: 0 16px;
  width: 100%;
  position: relative;
  .roleName {
    width: 400px;
    margin-bottom: 16px;
    span {
      display: inline-block;
    }
    .input {
      width: 250px;
    }
  }
  .config {
    border: 1px solid #e8e8e8;
    padding: 12px 16px;
    height: 150px;
    margin-bottom: 53px;
    overflow-y: auto;
    min-width: 807px;
    .title {
      margin-bottom: 8px;
      color: #666;
    }
    .content {
      display: flex;
      .sort {
        width: 50%;
        padding-left: 30px;
        .sortTitle {
        }
      }
    }
  }
  .roleContent {
    max-height: 620px;
    overflow-y: auto;
    .roleList {
      border: 1px solid #e8e8e8;
      padding: 12px 16px;
      height: 520px;
      margin-bottom: 20px;
      overflow-y: auto;
      min-width: 807px;
      .title {
        margin-bottom: 8px;
      }
      .desc {
        margin-bottom: 8px;
        color: #999;
      }
      .dataList {
        display: flex;
        flex-wrap: wrap;
        .treeList {
          width: 250px;
        }
      }
      .list {
        padding: 12px 24px;
        .content {
          margin-bottom: 10px;
          display: flex;
          .left,
          .right {
            width: 49%;
            overflow: hidden;
            .title {
              margin-bottom: 8px;
            }
          }
        }
      }
    }
    .dataRole {
      margin-top: 16px;
      height: 620px;
    }
  }

  .bottomBtn {
    position: fixed;
    bottom: 0;
    right: 0;
    width: 100%;
    text-align: right;
    border-top: 1px solid #e8e8e8;
    padding: 10px;
    background: #fff;
    z-index: 1;
  }
}
</style>